import {
  Component,
  Input,
  HostBinding,
  OnDestroy,
  OnInit,
  Optional,
} from '@angular/core';

import { ValidationObject } from '../element-base';
import { FormItemComponent } from '../form-item/form-item.component';

@Component({
  selector: 'fui-form-error',
  templateUrl: './form-error.component.html',
  styleUrls: ['./form-error.component.sass'],
})
export class FormErrorComponent implements OnInit, OnDestroy {
  @HostBinding('class.fui-form-error') hostClass = true;

  /** Validation results. */
  @Input()
  set validationResults(results: ValidationObject[]) {
    this.results = this.filterResults(results);
  }

  /** Validation error messages. */
  @Input() errorMsgs: string[] = [];

  results: ValidationObject[] = [];

  constructor(
    @Optional() private formItem?: FormItemComponent,
  ) { }

  ngOnInit() {
    if (this.formItem) {
      this.formItem.increFormError();
    }
  }

  ngOnDestroy() {
    if (this.formItem) {
      this.formItem.decreFormError();
    }
  }

  filterResults(results: ValidationObject[]) {
    const required = results.find((o) => o.key === 'required');
    // 如果存在required验证失败，则只显示required失败提示。
    // 没有必要把其他提示显示出来，其他输入验证无意义。
    if (required && required.value) {
      return [required];
    } else {
      return results;
    }
  }
}
